package com.hsogoo.study.leetcode.twosum;

import java.util.HashMap;
import java.util.Map;

/**
 * 第一题：两数之和
 * 解法：利用target和遍历数之差，在map匹配存在的值
 */
class Solution {

    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> container = new HashMap<Integer, Integer>();
        for(int i=0; i< nums.length; i++){
            int sub = target - nums[i];
            if(container.containsKey(sub)){
                int index = container.get(sub);
                return new int[]{index, i};
            }
            container.put(nums[i], i);
        }
        return null;
    }

    public static void main(String[] args) {
        int[] nums = {2, 7, 11, 15};
        int target = 9;
        Solution s = new Solution();
        int[] result = s.twoSum(nums, target);
        System.out.println(result[0] + "," + result[1]);
    }

}